import {
  Controller,
  Inject,
  UploadedFiles,
  UseInterceptors,
  Param,
  HttpException,
  HttpStatus,
  Post,
  Delete,
  Body,
} from '@nestjs/common';
import { AnyFilesInterceptor } from '@nestjs/platform-express';
import { MinioService } from 'nestjs-minio-client';
import { generateFileName, genFolderName } from '@/utils/file';
import { ConfigService } from '@nestjs/config';
import { MinioClientService } from './MinioClient.service';

@Controller('upload')
export class MinioClientController {
  @Inject(MinioService)
  private readonly minioService: MinioService;

  @Inject(ConfigService)
  private readonly configService: ConfigService;

  @Inject(MinioClientService)
  private readonly minioClientService: MinioClientService;

  private bucketName: string;

  constructor(configService: ConfigService) {
    this.bucketName = configService.get('minio.bucket');
  }

  @Post(':type?')
  @UseInterceptors(
    AnyFilesInterceptor({
      fileFilter: (req, file, cb) => {
        if (!file.mimetype.includes('image')) {
          cb(new HttpException('只能上传图片', HttpStatus.BAD_REQUEST), false);
        }
        cb(null, true);
      },
    }),
  )
  async uploadMinio(@UploadedFiles() files: any, @Param('type') type: string) {
    if (!files) {
      throw new HttpException('请先上传图片', HttpStatus.BAD_REQUEST);
    }
    const promises = files.map(async (file: Express.Multer.File) => {
      const buffer = file.buffer;
      const folderName = genFolderName(type);
      const fileName = generateFileName(file);
      const objectName = `${folderName}/${fileName}`;

      await this.minioService.client.putObject(
        this.bucketName,
        objectName,
        buffer,
      );

      return `http:///${this.configService.get(
        'minio.endpoint',
      )}:${this.configService.get('minio.port')}/${
        this.bucketName
      }/${objectName}`.replaceAll('//', '/');
    });
    return await Promise.all(promises);
  }

  @Delete()
  async deleteMinio(@Body('imgs') imgs: string[]) {
    await this.minioClientService.deleteMinioFile(imgs);
    return '删除成功';
  }
}
